# -*- coding: utf-8 -*-

def index():
    if session.auth:  # Is user logged in?
        login = session.auth.user.username
    else:
        login = None
        
    if session.flash:
        response.flash = session.flash
        session.flash = None

    cform = SQLFORM.factory(
        Field('player', requires=IS_NOT_EMPTY()))
    if cform.accepts(request.vars, session):
        response.flash = 'form accepted'
        redirect(URL('challenge', vars=dict(userid=login, player=cform.vars.player)))
    elif cform.errors:
        response.flash = 'form has errors'
    else:
        session.player = None

    match = db().select(db.match.ALL, orderby=~db.match.id)
    competitor = db().select(db.competitor.ALL, orderby=db.competitor.name_user|db.competitor.name_player)
    
    ladderadjust = local_import('ladderadjust', reload=True)
    ladder = ladderadjust.getLadderWinsLosses(db)

    return dict(login=login, ladder=ladder, competitor=competitor, match=match, cform=cform)

def challenge():
    dochallenge = local_import('dochallenge', reload=True)

    userid = request.vars.userid
    player = request.vars.player

    if dochallenge.scriptRunnable(logger, userid, player):
        select = db((db.competitor.name_user == userid) & (db.competitor.name_player == player)).select().first()
        if select:
            select.update_record(status='ready')
            session.flash = '%s/%s is readied in queue' % (userid, player)
        else:
            db.competitor.insert(status='ready', name_user=userid, name_player=player)
            # TODO: ENSURE BACKGROUND RUNNER IS RUNNING
            session.flash = '%s/%s is now in queue' % (userid, player)
    else:
        select = db((db.competitor.name_user == userid) & (db.competitor.name_player == player)).select().first()
        if select:
            select.update_record(status='benched')
        # Hack to notify of bad script; need to integrate flash with main index page
        session.flash = 'Login "%s" does not have a runnable player script "%s".' % (userid, player)

    redirect(URL('index'))

def runQueue():
    from subprocess import Popen
    Popen(['applications/icypc/private/dotask', 'runqueue.py'])
    redirect(URL('index'))

##
# Miscellaneous stubs--how many of these are required...?
##

def user(): return dict(form=auth())

def download(): return response.download(request, db)

def call():
    session.forget()
    return service()

@auth.requires_login()
def data():
    return dict(form=crud())

def error():
    return dict()
